package com.taofengsdk.okhttp;

import com.taofengsdk.okhttp.https.HttpsUtils;
import com.taofengsdk.okhttp.listener.DisposeDataHandle;
import com.taofengsdk.okhttp.listener.DisposeDataListener;
import com.taofengsdk.okhttp.response.CommonFileCallback;
import com.taofengsdk.okhttp.response.CommonJsonCallback;

import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * Created by tao on 17-3-12.
 *
 * @function 请求的发送，参数的配置，https的支持
 */

public class CommonOkHttpClient {
    private static final int TIME_OUT = 30;

    private static final OkHttpClient mOkHttpClient;

    //为client配置参数
    static {
        //创建client对象的构建者
        OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
        //为构建者填充超时时间
        okHttpBuilder.connectTimeout(TIME_OUT, TimeUnit.SECONDS);
        okHttpBuilder.readTimeout(TIME_OUT, TimeUnit.SECONDS);
        okHttpBuilder.writeTimeout(TIME_OUT, TimeUnit.SECONDS);
        //允许重定向
        okHttpBuilder.followRedirects(true);

        //https支持
        okHttpBuilder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        okHttpBuilder.sslSocketFactory(HttpsUtils.initSSLSocketFactory()
                , HttpsUtils.initTrustManager());

        //生成client对象
        mOkHttpClient = okHttpBuilder.build();
    }

    public static Call post(Request request, DisposeDataHandle handle) {
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new CommonJsonCallback(handle));

        return call;
    }

    public static Call get(Request request, DisposeDataHandle handle) {
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new CommonJsonCallback(handle));

        return call;
    }

    public static Call downloadFile(Request request, DisposeDataHandle handle){
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new CommonFileCallback(handle));

        return call;
    }

}
